<template>
  <div class="steve-content" :style="getWrapStyle">
    <slot></slot>
  </div>
</template>
<script lang="ts" setup>
import { useWindowSize } from '@vueuse/core';
import debounce from 'lodash/debounce';
import { computed, CSSProperties, ref, watch } from 'vue';

import { useSettingStore } from '@/store';

const { width: windowWidth, height: windowHeight } = useWindowSize();
const heightRef = ref(window.innerHeight);
const settingStore = useSettingStore();

// props
const props = defineProps({
  // 组件高度
  height: {
    type: Number,
    default: 0,
  },
  // 其他高度
  otherHeight: {
    type: Number,
    default: 0,
  },
});

const getWrapStyle = computed((): CSSProperties => {
  return {
    height: `${heightRef.value}px`,
  };
});

const computedStyle = getComputedStyle(document.documentElement);
const sizeXxxl = computedStyle.getPropertyValue('--td-comp-size-xxxl');
const paddingTBXxl = computedStyle.getPropertyValue('--td-comp-paddingTB-xl');

function getOuterHeight(dom: Element) {
  let h = 0;
  if (dom) {
    h = dom.clientHeight;
    const computedStyle = window.getComputedStyle(dom);
    h += parseInt(computedStyle.marginTop, 10);
    h += parseInt(computedStyle.marginBottom, 10);
    h += parseInt(computedStyle.borderTopWidth, 10);
    h += parseInt(computedStyle.borderBottomWidth, 10);
  }
  return h;
}

function calcHeight() {
  const { isUseTabsRouter, showBreadcrumb } = settingStore;
  const headerHeight = parseFloat(sizeXxxl);
  const navDom = document.querySelector('.t-tabs__nav');
  const navHeight = isUseTabsRouter ? getOuterHeight(navDom) : 0;
  const breadcrumbDom = document.querySelector('.t-breadcrumb');
  const breadcrumbHeight = showBreadcrumb ? getOuterHeight(breadcrumbDom) : 0;
  const contentPadding = parseFloat(paddingTBXxl) * 2;
  const top = headerHeight + navHeight + breadcrumbHeight + contentPadding;
  heightRef.value = window.innerHeight - top - props.otherHeight;
}

// 如果窗口大小发生变化
watch([windowWidth, windowHeight], debounce(calcHeight, 250));
watch([heightRef, () => settingStore.isUseTabsRouter, () => settingStore.showBreadcrumb], debounce(calcHeight, 250));

const emit = defineEmits(['update:height']);
watch(heightRef, () => {
  emit('update:height', heightRef.value);
});
calcHeight();
</script>
<style lang="less" scoped>
.steve-content {
  overflow: hidden;
}
</style>
